package com.naizhuai.ui.mianbusiness.setting;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.adapter.ManageDividerItemDecoration;
import com.naizhuai.ui.adapter.business.PersonRadarAbilityAdapterHolder;
import com.naizhuai.ui.adapter.management.UserAbilityAdapter;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.ui.components.LabelsView;
import com.naizhuai.ui.components.RadarData;
import com.naizhuai.ui.components.RadarView;
import com.naizhuai.ui.components.SingleLabelsView;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.setting.UserAbilityLabels;
import com.naizhuai.ui.entity.setting.UserRadarLabels;
import com.naizhuai.ui.mianbusiness.setting.presenter.UserPersonalApiStoreIml;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.MathUtils;
import com.naizhuai.util.NaizhuAILog;
import com.tencent.bugly.beta.Beta;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;

/**
 * 个人雷达图的页面详情
 */
public class PersonRadarActivity extends SwipeBackActivity implements View.OnClickListener {
    private static final String TAG = "PersonRadarActivity";

    @BindView(R.id.base_back_icon)
    ImageView backIcon;

    @BindView(R.id.user_thumb)
    CircleImageView userThumb;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_level)
    TextView userLevel;
    @BindView(R.id.progress_text)
    TextView userProcess;

    @BindView(R.id.radar_view)
    RadarView userRadar;
    //    @BindView(R.id.ability_labels_list)
//    LabelsView labelsView;

    @BindView(R.id.ability_labels_list)
    RecyclerView abilityLabelsList;
    private List<String> abilitySourceList;
    private PersonRadarAbilityAdapterHolder abilityHolder;

    @BindView(R.id.user_activity_number)
    TextView userActivityNumber;
    @BindView(R.id.user_ability_field_list)
    RecyclerView abilityList;
    private UserAbilityAdapter detailsAdapter;
    @BindView(R.id.level_process_back)
    ImageView processBack;
    @BindView(R.id.level_process_content)
    ImageView processContent;

    @BindView(R.id.estimate_action)
    TextView esAction;
    @BindView(R.id.join_action)
    TextView joinAction;
    @BindView(R.id.charge_task)
    TextView chargeTask;
    @BindView(R.id.join_task)
    TextView joinTask;

    private String dataDetailsFormat;

    private UserRadarLabels userRadarLabels;

    private String userId;

    private List<UserAbilityLabels.UserAbilityItemBean> UserAbilities;


    private static int TIME_DURATION = 20;
    private static int TIME_INTERVAL = 18;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBaseData();
        initBaseView();
        userRadar.post(new Runnable() {
            @Override
            public void run() {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) userRadar.getLayoutParams();
                params.height = userRadar.getWidth();
                userRadar.setLayoutParams(params);
                requestGrowData();
                requestRadarData();
            }
        });

    }

    public static void startActivity(String actionId, Context mContext) {
        IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, actionId, mContext, PersonRadarActivity.class);
    }

    private void requestRadarData() {
        UserPersonalApiStoreIml.getInstance().getRadarMsgById(userId).subscribe(new Observer<UserRadarLabels>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(UserRadarLabels userRadarLabels) {
                refreshRadarData(userRadarLabels);
            }
        });
    }

    private void requestGrowData() {
        UserPersonalApiStoreIml.getInstance().getGrowById(userId).subscribe(new Observer<UserAbilityLabels>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UserAbilityLabels userAbilityLabels) {
                refreshGrowData(userAbilityLabels);
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (userRadarLabels != null) {
            refreshRadarData(userRadarLabels);
        }
    }

    private void refreshRadarData(UserRadarLabels radarLabels) {
        this.userRadarLabels = radarLabels;
        userActivityNumber.setText(userRadarLabels.getActivityScore());
        userRadar.setEmptyHint("无数据");
        userRadar.setMaxValue(100f);
        userRadar.setDrawValueText(false);
        userRadar.setLayer(3);
        userRadar.setRotationEnable(false);

        List<String> vertexText = new ArrayList<>();
        Collections.addAll(vertexText, "视野", "策划", "执行", "组织", "激励", "协作");
        userRadar.setVertexText(vertexText);

        List<Integer> res = new ArrayList<>();
        Collections.addAll(res, R.mipmap.radar_number_back_gray, R.mipmap.radar_number_back_green,
                R.mipmap.radar_number_back_red, R.mipmap.radar_number_back_yellow);
        userRadar.setVertexIconResid(res);
        List<Integer> intList = new ArrayList<>();
        Collections.addAll(intList, RadarView.VERTEX_ICON_POSITION_RIGHT, RadarView.VERTEX_ICON_POSITION_BOTTOM, RadarView.VERTEX_ICON_POSITION_BOTTOM,
                RadarView.VERTEX_ICON_POSITION_RIGHT, RadarView.VERTEX_ICON_POSITION_BOTTOM, RadarView.VERTEX_ICON_POSITION_BOTTOM);
        userRadar.setVertexIconPosition(intList);

//        List<Float> values = new ArrayList<>();
//        Collections.addAll(values, 3f, 6f, 2f, 7f, 5f, 1f, 9f, 3f, 8f, 5f);
//        RadarData data = new RadarData(values);
//        mRadarView.addData(data);

        //确定显示的个数
        UserRadarLabels.QuarterScore currentScore = userRadarLabels.getCurrentQuarterScore();
        UserRadarLabels.QuarterScore lastScore = userRadarLabels.getLastQuarterScore();
        NaizhuAILog.e("currentScore=" + currentScore.toString());
        NaizhuAILog.e("lastScore=" + lastScore.toString());
        //上期数据
        List<Float> values2 = new ArrayList<>();
        Collections.addAll(values2, Float.parseFloat(lastScore.getFieldScore()), Float.parseFloat(lastScore.getPlanScore()), Float.parseFloat(lastScore.getExecuteScore()),
                Float.parseFloat(lastScore.getOrganizeScore()), Float.parseFloat(lastScore.getEncourageScore()), Float.parseFloat(lastScore.getOrganizeScore()));
        RadarData data2 = new RadarData(values2, R.color.radar_view_color_past);
        data2.setValueTextEnable(true);
        data2.setVauleTextColor(R.color.info_achieve_color);
        data2.setValueTextSize(dp2px(10));
        data2.setLineWidth(dp2px(1));
        userRadar.addData(data2);
        //当前数据
        List<Float> values1 = new ArrayList<>();
        Collections.addAll(values1, Float.parseFloat(currentScore.getFieldScore()), Float.parseFloat(currentScore.getPlanScore()), Float.parseFloat(currentScore.getExecuteScore()),
                Float.parseFloat(currentScore.getOrganizeScore()), Float.parseFloat(currentScore.getEncourageScore()), Float.parseFloat(currentScore.getOrganizeScore()));
        RadarData data1 = new RadarData(values1, R.color.radar_view_color);
        data1.setValueTextEnable(true);
        data1.setVauleTextColor(R.color.info_achieve_color);
        data1.setValueTextSize(dp2px(10));
        data1.setLineWidth(dp2px(1));
        userRadar.addData(data1);
    }

    @Override
    protected void onDestroy() {
        userRadar.clearRadarData();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        userRadar.clearRadarData();
        super.onPause();
    }

    @Override
    protected void onStop() {
        userRadar.clearRadarData();
        super.onStop();
    }

    private void refreshGrowData(UserAbilityLabels userAbilityLabels) {
        UserAbilityLabels.QuarterDetailsData currentData = userAbilityLabels.getCurrentQuarter();
        UserAbilityLabels.QuarterDetailsData totalData = userAbilityLabels.getTotalQuarter();

        esAction.setText(String.format(dataDetailsFormat, currentData.getVerifyAction(), totalData.getVerifyAction()));
        joinAction.setText(String.format(dataDetailsFormat, currentData.getJoinedAction(), totalData.getJoinedAction()));
        chargeTask.setText(String.format(dataDetailsFormat, currentData.getManagerTask(), totalData.getManagerTask()));
        joinTask.setText(String.format(dataDetailsFormat, currentData.getJoinedTask(), totalData.getJoinedTask()));

        NaizhuAILog.e("userAbilityLabels.getUserThumb=" + userAbilityLabels.getUserThumb());
        ImageUtils.glideThumbViewByUrl(this, userThumb, userAbilityLabels.getUserThumb());
        userName.setText(userAbilityLabels.getUsername());
        userLevel.setText(String.format("LV%1$s", userAbilityLabels.getUserlevel()));
        userProcess.setText(String.format("%1$s/%2$s", userAbilityLabels.getExperience(), userAbilityLabels.getTotalExperience()));
        initActionProcess(Float.parseFloat(userAbilityLabels.getExperience()) / Float.parseFloat(userAbilityLabels.getTotalExperience()));

//        List<String> labels = new ArrayList<>();
//        labels.addAll(userAbilityLabels.getAchievements());
//        labelsView.setHook(true);
//        labelsView.setLabels(labels, new LabelsView.LabelTextProvider<String>() {
//            @Override
//            public CharSequence getLabelText(SingleLabelsView label, int position, String data) {
//                return data;
//            }
//        });

        if (userAbilityLabels.getAchievements() != null && userAbilityLabels.getAchievements().size() > 0) {
            abilitySourceList.addAll(userAbilityLabels.getAchievements());
            abilityHolder.notifyDataSetChanged();
        }
        UserAbilities.clear();
        UserAbilities.addAll(userAbilityLabels.getAbility());
        detailsAdapter.notifyDataSetChanged();
    }

    private void initActionProcess(float radius) {
        processBack.post(new Runnable() {
            @Override
            public void run() {
                int totalWidth = processBack.getWidth();
                int proTotalWidth = (int) (totalWidth * radius);
                int processWidth = processContent.getWidth();
                if (processWidth < proTotalWidth) {
                    new Handler().post(new PercentRunnable(proTotalWidth, processWidth, (proTotalWidth - processWidth) / TIME_DURATION, processContent));
                }
            }
        });
    }

    private void initBaseData() {
        abilitySourceList = new ArrayList<>();
        UserAbilities = new ArrayList<>();
        dataDetailsFormat = getString(R.string.user_grew_percent);
        userId = getIntent().getStringExtra(PersonUserBean.USER_ID_KEY);
    }

    private void initBaseView() {
        initRecyclerViewList();
    }

    private void initRecyclerViewList() {
        detailsAdapter = new UserAbilityAdapter(this, UserAbilities);
        abilityList.setNestedScrollingEnabled(false);
        abilityList.setHasFixedSize(true);
        abilityList.setLayoutManager(new LinearLayoutManager(this));
        abilityList.setItemAnimator(new DefaultItemAnimator());
        abilityList.setAdapter(detailsAdapter);


        abilityHolder = new PersonRadarAbilityAdapterHolder(this, abilitySourceList);
        abilityLabelsList.setHasFixedSize(true);
        abilityLabelsList.setNestedScrollingEnabled(false);
        abilityLabelsList.setLayoutManager(new GridLayoutManager(this, 4));
        abilityLabelsList.setItemAnimator(new DefaultItemAnimator());
        abilityLabelsList.setAdapter(abilityHolder);
    }

    @OnClick({R.id.base_back_icon, R.id.radar_view})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_back_icon:
                onBackPressed();
                break;
            case R.id.radar_view:
                if (userRadar.isEmpty()) {
                    requestRadarData();
                }
                break;
        }
    }


    class PercentRunnable implements Runnable {
        private int total;
        private int source;
        private int interAdd;
        private View mView;

        public PercentRunnable(int total, int source, int interAdd, View mView) {
            this.total = total;
            this.source = source;
            this.interAdd = interAdd;
            this.mView = mView;
        }

        @Override
        public void run() {
            NaizhuAILog.e("start....");
            if (source < total) {
                source += interAdd;
                source = source > total ? total : source;
            } else
                return;
            if (source <= total) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mView.getLayoutParams();
                params.width = source;
                mView.setLayoutParams(params);
                new Handler().postDelayed(new PercentRunnable(total, source, interAdd, mView), TIME_INTERVAL);
            }
        }
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_radar_layout;
    }

    private float dp2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return dpValue * scale + 0.5f;
    }

}
